package aryn.framework.io.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;


public class ZipHelper {
	
	public static void zip(String resourceToZip, String filenameZipped) {
		try {
			ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(filenameZipped)));
			File f = new File(resourceToZip);
			
			File[] listaFiles = f.listFiles();
			
			for(int i=0; i < listaFiles.length; i++){
				File currFile = listaFiles[i];
				ZipHelper.compress(currFile, "", zos);
			}	  
			zos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
 private static void compress(File f, String path, ZipOutputStream zos) throws IOException {

    boolean isDirectory = f.isDirectory();
    final String nextPath = path + f.getName() + (isDirectory ? "/" : "");
   
     ZipEntry zipEntry = new ZipEntry(nextPath);
     zos.putNextEntry(zipEntry);

     if(isDirectory) {
         File[] child = f.listFiles();
        //ricorsione per ogni figlio
        for(int i = 0; i < child.length; i++) 
             compress(child[i], nextPath, zos);
         
     } else if(f.isFile()) {
         FileInputStream fis = new FileInputStream(f);
         byte[] readBuffer = new byte[4096];
         int bytesIn = 0;
       
      //insert del file nell'ultima zipEntry dello ZipOutputStream 
         while ((bytesIn = fis.read(readBuffer)) != -1) 
             zos.write(readBuffer, 0, bytesIn);
       
         fis.close();
    }
  }
 }